package com.elitel.frame.base.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.elitel.frame.base.service.BaseReptempletService;
import com.elitel.frame.core.util.FileControlUtil;
import com.elitel.frame.main.entity.BaseReptemplate;
import com.elitel.frame.main.entity.vo.PageResponseVo;

/**
 * 
 * <pre>@ProjectName：frame-base-web    
 * @ClassName：BaseReptempletController    
 * @Description: TODO(报表模板管理)    
 * @author：FanWenquan  
 * @date：2017年8月31日 上午10:51:04       
 * @version </pre>
 */
@Controller
@RequestMapping("/system/reptemplet")
public class BaseReptempletController {
	
	private static final Logger logger = LoggerFactory.getLogger(BaseReptempletController.class);
	
	@Autowired
	private BaseReptempletService baseReptempletService;
	
	/**
	 * <pre>selectReptempletList(查询所有模板)   
	 * @author：FanWenquan    
	 * @date：2017年8月31日 上午10:51:28   
	 * @return</pre>
	 */
	@RequestMapping("/selectReptempletList")
	@ResponseBody
	public Object selectReptempletList() {
		List<BaseReptemplate> list = baseReptempletService.selectReptempleList();
		return list;
	}
	
	/**
	 * <pre>queryReptemplateByPaging(根据条件查询模板信息)   
	 * @author：FanWenquan    
	 * @date：2017年8月31日 上午11:50:43   
	 * @param seachTxt
	 * @param pageNo
	 * @param pageSize
	 * @return</pre>
	 */
	@RequestMapping("/queryReptemplate")
	@ResponseBody
	public Object queryReptemplateByPaging(String searchTxt, String pageNo, String pageSize ) {
		PageResponseVo<BaseReptemplate> pageResponseVo = new PageResponseVo<BaseReptemplate>();
		Long count = baseReptempletService.selectCount(searchTxt);
		List<BaseReptemplate> list = baseReptempletService.queryReptemplateByPaging(searchTxt, pageNo, pageSize);
		pageResponseVo.setRows(list);
		pageResponseVo.setTotal(count.intValue());
		return pageResponseVo;
	}
	
	/**
	 * <pre>insertReptemplate(添加模板信息)   
	 * @author：FanWenquan    
	 * @date：2017年8月31日 上午11:51:08   
	 * @param baseReptemplet
	 * @return</pre>
	 */
	@RequestMapping("/insertReptemplate")
	public @ResponseBody String insertReptemplate(HttpServletRequest request,@RequestParam("file") MultipartFile[] files,
			 String templatename, String serviceid, String templatedesc) {
		String templateurl = null;
		String jrxmlurl = null;
		if(files != null && files.length > 0 ){
			
			for (MultipartFile file : files) {
	        String uploadRootPath = request.getSession().getServletContext().getRealPath("/WEB-INF/jasper");
	        //System.out.println("jasperRootPath=" + uploadRootPath);
	        
	        File uploadRootDir = new File(uploadRootPath);
	        // Create directory if it not exists.
	        if (!uploadRootDir.exists()) {
	            uploadRootDir.mkdirs();
	        }
	        String lname = file.getOriginalFilename();
	        if(lname.contains(".jasper")) {
	        	templateurl="/WEB-INF/jasper/"+lname;
	        }else if(lname.contains(".jrxml")) {
	        	jrxmlurl="/WEB-INF/jasper/"+lname;
	        }
	        
	        if (lname != null && lname.length() > 0) {
                try {
                    byte[] bytes = file.getBytes();
                    // Create the file on server
                    File serverFile = new File(uploadRootDir.getAbsolutePath()
                            + File.separator + lname);
 
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
			}
		}
		BaseReptemplate baseReptemplet = new BaseReptemplate();
		String guid = UUID.randomUUID().toString();
		baseReptemplet.setGuid(guid);
		baseReptemplet.setTemplateName(templatename);
		baseReptemplet.setServicecode(serviceid);
		baseReptemplet.setTemplateDesc(templatedesc);
		baseReptemplet.setTemplateUrl(templateurl);
		baseReptemplet.setJrxmlUrl(jrxmlurl);
		int size = baseReptempletService.insertReptemplate(baseReptemplet);
		return String.valueOf(size);
	}
	
	/**
	 * <pre>selectReptemplateByKey(根据主键查询模板信息)   
	 * @author：FanWenquan    
	 * @date：2017年8月31日 上午11:56:09   
	 * @param guid
	 * @return</pre>
	 */
	@RequestMapping("/selectReptemplateByKey")
	@ResponseBody
	public Object selectReptemplateByKey(String guid) {
		BaseReptemplate baseReptemplet = baseReptempletService.selectReptemplateByKey(guid);
		return baseReptemplet;
	}
	
    /**
     * 
        * @Title: getReptemplateByServiceid  
        * @Description: TODO(通过服务获取模板)  
        * @param @param serviceid
        * @param @return
        * @return Object
     */
	@RequestMapping("/getReptemplateByServiceid")
	@ResponseBody
	public Object getReptemplateByServiceid(String serviceid) {
		BaseReptemplate baseReptemplet = baseReptempletService.getReptemplateByServiceid(serviceid);
		return baseReptemplet;
	}
	
	/**
	 * <pre>updateReptemplate(修改模板信息)   
	 * @author：FanWenquan    
	 * @date：2017年8月31日 上午11:51:29   
	 * @param baseReptemplet
	 * @return</pre>
	 */
	@RequestMapping("/updateReptemplate")
	public  @ResponseBody String updateReptemplate(HttpServletRequest request,@RequestParam("file") MultipartFile[] files,
			String guid, String templatename, String serviceid, String templatedesc) {
		String templateurl = null;
		String jrxmlurl = null;
		if(files != null && files.length > 0){
			BaseReptemplate baseReptemplet = baseReptempletService.selectReptemplateByKey(guid);
			String deljasperurl = request.getSession().getServletContext().getRealPath(baseReptemplet.getTemplateUrl());
			String deljrxmlurl = request.getSession().getServletContext().getRealPath(baseReptemplet.getJrxmlUrl());
			
				try {
					if(deljasperurl != null && deljasperurl != ""){
					FileControlUtil.deleteFile(deljasperurl);
					}
					if(deljrxmlurl != null && deljrxmlurl != ""){
						FileControlUtil.deleteFile(deljrxmlurl);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			 // Root Directory.
			for (MultipartFile file : files) {
	        String uploadRootPath = request.getSession().getServletContext().getRealPath("/WEB-INF/jasper");
//	        System.out.println("jasperRootPath=" + uploadRootPath);
	        
	        File uploadRootDir = new File(uploadRootPath);
	        // Create directory if it not exists.
	        if (!uploadRootDir.exists()) {
	            uploadRootDir.mkdirs();
	        }
	        String lname = file.getOriginalFilename();
	        if(lname.contains(".jasper")) {
	        	templateurl="/WEB-INF/jasper/"+lname;
	        }else if(lname.contains(".jrxml")) {
	        	jrxmlurl="/WEB-INF/jasper/"+lname;
	        }
	        if (lname != null && lname.length() > 0) {
                try {
                    byte[] bytes = file.getBytes();
                    // Create the file on server
                    File serverFile = new File(uploadRootDir.getAbsolutePath()
                            + File.separator + lname);
 
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                    //System.out.println("Write file: " + serverFile);
                } catch (Exception e) {
                    //System.out.println("Error Write file: " + lname);
                    logger.error(e.getMessage(), e);
                }
            }
		 }
		}
		BaseReptemplate baseReptemplet = new BaseReptemplate();
		baseReptemplet.setGuid(guid);
		baseReptemplet.setTemplateName(templatename);
		baseReptemplet.setServicecode(serviceid);
		baseReptemplet.setTemplateDesc(templatedesc);
		baseReptemplet.setTemplateUrl(templateurl);
		baseReptemplet.setJrxmlUrl(jrxmlurl);
		int size = baseReptempletService.updateReptemplate(baseReptemplet);
		return String.valueOf(size);
	}
	
	/**
	 * <pre>deleteReptemplate(删除模板信息及属性信息)   
	 * @author：FanWenquan    
	 * @date：2017年8月31日 上午11:51:50   
	 * @param guid
	 * @return</pre>
	 */
	@RequestMapping("/deleteReptemplate")
	@ResponseBody
	public Object deleteReptemplate(String guid, HttpServletRequest request) {
		Boolean li = false;
		try {
			 baseReptempletService.deleteReptemplate(guid, request);
			 li = true;
		} catch (Exception e) {
			 li = false;
			 logger.error(e.getMessage(), e);
		}
		
		return li;
	}
}
